package org.jeecg.modules.inspect.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.apache.ibatis.logging.Log;
import org.apache.ibatis.logging.LogFactory;
import org.apache.logging.log4j.util.Strings;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.FillRuleUtil;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.modules.inspect.entity.*;
import org.jeecg.modules.inspect.service.*;
import org.jeecg.modules.inspect.util.SmsUtil;
import org.jeecg.modules.system.entity.SysDepart;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.mapper.SysUserMapper;
import org.jeecg.modules.system.service.ISysDepartService;
import org.jeecg.modules.system.service.ISysUserService;
import org.jeecg.modules.system.vo.SysUserDepVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description: 任务分配
 * @Author: jeecg-boot
 * @Date:   2023-11-22
 * @Version: V1.0
 */
@Service
public class TaskAllocServiceImpl implements TaskAllocService {

    protected Log log = LogFactory.getLog(getClass());

    @Value("${timeStandard}")
    private String timeStandard;
    @Value("${spring.redis.port:6379}")
    private String redisPort;
    @Value("${spring.redis.host:127.0.0.1}")
    private String redisHost;
    @Autowired
    private RedisUtil redisUtil;
    @Resource
    private ISysBaseAPI sysBaseApi;
    @Resource
    private IInsTaskService insTaskService;
    @Resource
    private IInsTaskItemService insTaskItemService;
    @Resource
    private IInsRuleService insRuleService;
    @Resource
    private IInsRuleLineService insRuleLineService;
    @Resource
    private IInsRuleDutyService insRuleDutyService;
    @Resource
    private IInsLineService insLineService;
    @Resource
    private IInsLinePointService insLinePointService;
    @Resource
    private IInsPointService insPointService;

    @Resource
    private IInsClassesService insClassesService;
    @Resource
    private IInsClassesUserService insClassesUserService;
    @Resource
    private IInsClassesSpecialService insClassesSpecialService;
    @Resource
    private IInsClassesCommonService insClassesCommonService;
    @Resource
    private IInsClassesSpecialDateService insClassesSpecialDateService;
    @Resource
    private IInsClassesSpecialDateSubService insClassesSpecialDateSubService;
    @Resource
    private IInsClassesLineService insClassesLineService;
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private ISysDepartService sysDepartService;
    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private IInsDeleteBackupService insDeleteBackupService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void yearTask() {
        // 年度
        Date taskBegin = DateUtil.offsetHour(DateUtil.beginOfYear(new Date()), 8);
        Date taskEnd = DateUtil.offsetHour(DateUtil.endOfYear(new Date()), 8);
        // 任务分配
        this.taskAlloc("1", taskBegin, taskEnd);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void quarterTask() {
        // 季度
        Date taskBegin = DateUtil.offsetHour(DateUtil.beginOfQuarter(new Date()), 8);
        Date taskEnd = DateUtil.offsetHour(DateUtil.endOfQuarter(new Date()), 8);

        // 任务分配
        this.taskAlloc("2", taskBegin, taskEnd);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void monthTask() {
        // 月度
        Date taskBegin = DateUtil.offsetHour(DateUtil.beginOfMonth(new Date()), 8);
        Date taskEnd = DateUtil.offsetHour(DateUtil.endOfMonth(new Date()), 8);

        // 任务分配
        this.taskAlloc("3", taskBegin, taskEnd);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void weekTask() {
        // 星期
        Date taskBegin = DateUtil.offsetHour(DateUtil.beginOfWeek(new Date()), 8);
        Date taskEnd = DateUtil.offsetHour(DateUtil.endOfWeek(new Date()), 8);

        // 任务分配
        this.taskAlloc("4", taskBegin, taskEnd);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void dayTask() {
        // 日
        Date taskBegin = DateUtil.offsetHour(DateUtil.beginOfDay(new Date()), 8);
        Date taskEnd = DateUtil.offsetHour(DateUtil.endOfDay(new Date()), 8);

        // 任务分配
        this.taskAlloc("5", taskBegin, taskEnd);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void classTask() {
        int offSet = 8;
        if(StringUtils.isNotBlank(timeStandard)){
            offSet = Integer.parseInt(timeStandard);
        }
        // 日
        Date taskBegin = DateUtil.offsetHour(DateUtil.beginOfDay(new Date()), offSet);
        Date taskEnd = DateUtil.offsetHour(DateUtil.endOfDay(new Date()), offSet);

        try{
            // 任务分配
            this.taskAllocByClasses("5", taskBegin, taskEnd);
        }catch (Exception e){
            e.printStackTrace();
        }
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void dutyTask() {
        // 排班
        Date taskBegin = DateUtil.offsetHour(DateUtil.beginOfDay(new Date()), 8);
        Date taskEnd = DateUtil.offsetHour(DateUtil.endOfDay(new Date()), 8);

        // 任务分配
        this.taskAlloc("6", taskBegin, taskEnd);
    }

    /**
     * 每晚59分时获取下一日是否为节假日数据
     */
    @Override
    public void holidays() {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        //获取明天的时间
        Date tomorrow = new Date(new Date().getTime() + (24 * 60 * 60 * 1000));
        String tomorrowData = new SimpleDateFormat("yyyy-MM-dd").format(tomorrow);
        String now = new SimpleDateFormat("yyyy-MM-dd").format(new Date());

        String url = "https://apis.tianapi.com/jiejiari/index?key=3950b924e669b8044168c5a91787fb4e&date="+tomorrowData+","+now+"&type=0";
        HttpPost httpPost = new HttpPost(url);

        try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
            HttpEntity entity = response.getEntity();
            String result = EntityUtils.toString(entity);
            JSONObject resJson = JSONObject.parseObject(result);
            if(!"200".equals(resJson.get("code").toString())){
                throw new RuntimeException("获取节假日失败，"+resJson.get("msg").toString());
            }
            JSONArray list = (JSONArray)((JSONObject)resJson.get("result")).get("list");
            if(!list.isEmpty()){
                for (Object o : list) {
                    JSONObject j = (JSONObject)o;
                    String date = j.get("date").toString();
                    String isnotwork = j.get("isnotwork").toString();//是否需要上班，0为工作日，1为休息日
                    redisUtil.set(date+"_isnotwork", isnotwork);
                }
            }
            System.out.println(result);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    private void taskAlloc(String executeCycle, Date taskBegin, Date taskEnd) {
        // 启用的规则
        List<InsRule> ruleList = insRuleService.list(Wrappers.<InsRule>lambdaQuery()
                .eq(InsRule::getRuleStatus, "1").eq(InsRule::getExecuteCycle, executeCycle));

        if(CollUtil.isNotEmpty(ruleList)) {
            for(InsRule rule : ruleList) {
                // start
                Integer executeNum = rule.getExecuteNum();

                // 执行几次生成几个任务
                for(int i = 0; i < executeNum; i++) {
                    // start
                    // 线路
                    List<InsRuleLine> ruleLines = insRuleLineService.list(Wrappers.<InsRuleLine>lambdaQuery().eq(InsRuleLine::getRuleId, rule.getId()));
                    if(CollUtil.isNotEmpty(ruleLines)) {
                        for(InsRuleLine ruleLine : ruleLines) {
                            InsLine insLine = insLineService.getById(ruleLine.getLineId());
                            // 一条线路一个任务
                            if(null != insLine) {
                                InsTask insTask = new InsTask();
                                BeanUtil.copyProperties(rule, insTask, CommonConstant.IGNORE_PROPERTIES);
                                insTask.setRuleId(rule.getId());
                                JSONObject formData = new JSONObject();
                                String taskNo = (String) FillRuleUtil.executeRule("shop_order_num",formData);


                                insTask.setTaskName(rule.getRuleName() + insLine.getLineName() + "巡检任务");
                                insTask.setTaskType(rule.getRuleType());
                                insTask.setTaskNo(taskNo);
                                insTask.setTaskStatus("1");
                                insTask.setTaskBegin(taskBegin);
                                insTask.setTaskEnd(taskEnd);
                                insTask.setInspectedNum(0);

                                // 值班部门
                                if("6".equals(executeCycle)) {
                                    // 值班
                                    int dayOfWeek = DateUtil.dayOfWeek(new Date());

                                    List<InsRuleDuty> dutyList = insRuleDutyService.list(Wrappers.<InsRuleDuty>lambdaQuery()
                                            .eq(InsRuleDuty::getRuleId, rule.getId()).eq(InsRuleDuty::getWeek, dayOfWeek));

                                    if(CollUtil.isNotEmpty(dutyList)) {
                                        insTask.setDeptId(dutyList.get(0).getDeptId());
                                    }
                                }
                                insTaskService.save(insTask);

                                // 一条线路的所有点位
                                List<InsLinePoint> linePoints = insLinePointService.list(Wrappers.<InsLinePoint>lambdaQuery().eq(InsLinePoint::getLineId, ruleLine.getLineId()));

                                if(CollUtil.isNotEmpty(linePoints)) {
                                    for(InsLinePoint linePoint : linePoints) {
                                        InsPoint insPoint = insPointService.getById(linePoint.getPointId());
                                        if(null != insPoint) {
                                            InsTaskItem taskItem = new InsTaskItem();
                                            taskItem.setItemName(insPoint.getPointName());
                                            taskItem.setItemStatus("1");
                                            taskItem.setTaskId(insTask.getId());
                                            taskItem.setLineId(ruleLine.getLineId());
                                            taskItem.setPointId(insPoint.getId());
                                            insTaskItemService.save(taskItem);
                                        }
                                    }
                                    //总点位数
                                    insTask.setPointNum(linePoints.size());
                                    insTaskService.updateById(insTask);
                                }
                            }
                        }
                    }
                    // end

                }

                // ==================== 发送短信开始 ===============================
                String phones = "";
                String departId = sysBaseApi.getDepartIdsByOrgCode("A06");

                // 厂领导部门
                if(StrUtil.isNotEmpty(departId)) {
                    if("6".equals(executeCycle)) {
                        // 排班部门是厂领导
                        // String taskDeptId = rule.getDepartId();
                        int dayOfWeek = DateUtil.dayOfWeek(new Date());

                        List<InsRuleDuty> dutyList = insRuleDutyService.list(Wrappers.<InsRuleDuty>lambdaQuery()
                                .eq(InsRuleDuty::getRuleId, rule.getId()).eq(InsRuleDuty::getWeek, dayOfWeek));

                        if(CollUtil.isNotEmpty(dutyList)) {
                            String taskDeptId = dutyList.get(0).getDeptId();

                            if(taskDeptId.equals(departId)) {
                                // 厂领导部门下所有人员信息
                                List<String> userPhones = sysBaseApi.getUserPhoneByDeptId(departId);
                                if(CollUtil.isNotEmpty(userPhones)) {
                                    phones = String.join(",", userPhones.stream().map(String::valueOf).collect(Collectors.toList()));
                                }
                            }
                        }
                    } else {
                        String roleId = rule.getRoleId();
                        // 角色下所有人员
                        List<String> userNames = sysBaseApi.getUserByRoleId(roleId);

                        if(CollUtil.isNotEmpty(userNames)) {
                            List<String> sendPhones = new ArrayList<>();
                            for(String userName : userNames) {
                                // 查询人员所在部门是否为厂领导
                                List<String> departIds = sysBaseApi.getDepartIdsByUsername(userName);
                                if(departIds.contains(departId)) {
                                    LoginUser loginUser = sysBaseApi.getUserByName(userName);
                                    sendPhones.add(loginUser.getPhone());
                                }
                            }
                            if(CollUtil.isNotEmpty(sendPhones)) {
                                phones = String.join(",", sendPhones.stream().map(String::valueOf).distinct().collect(Collectors.toList()));
                            }
                        }
                    }
                }

                if(StrUtil.isNotEmpty(phones)) {
                    log.debug("发送短信提醒厂领导：" + phones);

                    // 发送厂领导任务生成短信提醒
                    String smsContent = "您有新的走动式巡检任务生成，截止日期" + DateUtil.format(taskEnd, "yyyy-MM-dd HH:mm:ss") + "请注意查收！";
                    SmsUtil.sendMas(phones.split(","), smsContent);

                    //try {
                    //    log.debug("发送短信提醒人员：" + phones);
                    //    Client client = Client.getInstance( );
                    //    // 登录地址需另外提供
                    //    boolean isLoggedin = client.login( "http://112.35.4.197:15000", "ypoa", "ypoadxfs", "永坪炼油厂" );
                    //    if( isLoggedin ) {
                    //        log.debug("发送短信登录成功");
                    //    } else {
                    //        log.debug("发送短信登录失败");
                    //        client.login( "http://112.35.4.197:15000", "ypoa", "ypoadxfs", "永坪炼油厂" );
                    //    }
                    //
                    //    // 普通短信：new String[]{ "18292100130" }
                    //    int rt = client.sendDSMS(phones.split(",") , "您有新的走动式巡检任务生成，截止日期" +
                    //            DateUtil.format(taskEnd, "yyyy-MM-dd HH:mm:ss") + "请注意查收！", "123", 1, "hysyRh6yt", null, true );
                    //    log.debug("发送短信返回值:" + rt);
                    //
                    //} catch (Exception e) {
                    //    e.printStackTrace();
                    //    log.error("发送短信出错" + e.getMessage());
                    //}
                }
                // 发送短信结束

            }
        }
    }

    private void taskAllocByClasses(String executeCycle, Date taskBegin, Date taskEnd) {
        //查询全部班次
        //查询校验特殊日期
        List<InsClassesSpecialDateSub> specialDates = insClassesSpecialDateSubService.list();
        boolean isSpeci = false;//是否是特殊日期
        if(CollectionUtils.isNotEmpty(specialDates)){
            List<InsClassesSpecialDateSub> collect = specialDates.stream()
                    .filter(o -> isToday(o.getSpecialTime())).collect(Collectors.toList());
            if(CollectionUtils.isNotEmpty(collect)){
                isSpeci = true;
            }
        }
        //获取当前星期数
//        Calendar calendar = Calendar.getInstance();
//        int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK); // 获取当前星期的值，范围为1-7，1代表星期日，2代表星期一，以此类推
//        if(dayOfWeek==1 || dayOfWeek==7){
//            isSpeci = true;
//        }
        //查询班次
        List<InsClasses> classesList = insClassesService.list();
        //查询人员
        List<InsClassesUser> userList = insClassesUserService.list();
        if(CollectionUtils.isEmpty(userList))  userList = new ArrayList<>();
        userList = userList.stream().filter(o-> StringUtils.isNotBlank(o.getClassId())).collect(Collectors.toList());
        Map<String, List<InsClassesUser>> userByClassIdValue = userList.stream().filter(o-> StringUtils.isNotBlank(o.getClassId())).collect(Collectors.groupingBy(o -> o.getClassId()));
        //查询系统全部人员
        List<String> userIdss = userList.stream()
                .filter(o->StringUtils.isNotBlank(o.getUserId()) && StringUtils.isNotBlank(o.getClassId()) )
                .map(o -> o.getUserId()).collect(Collectors.toSet()).stream().collect(Collectors.toList());
        List<SysUser> sysUserList = new ArrayList<>();
        for (String id : userIdss) {
            sysUserList.add(sysUserService.getUserByName(id));
        }
        //查询系统人员部门
        List<String> uids = sysUserList.stream().map(o -> o.getId()).collect(Collectors.toList());
        List<SysUserDepVo> sysDeptList = sysUserMapper.getDepNamesByUserIds(uids);
        if(CollectionUtils.isEmpty(sysDeptList)){
            sysDeptList = new ArrayList<>();
        }
        Map<String, String> userNameByIdValue = sysUserList.stream().collect(Collectors.toMap(o -> o.getId(), o -> o.getUsername(), (p, e) -> e));
        //查询线路
        List<InsClassesLine> lineList = insClassesLineService.list();
        if(CollectionUtils.isEmpty(lineList))  lineList = new ArrayList<>();
        Map<String, List<InsClassesLine>> lineByClassIdValue = lineList.stream().filter(o-> StringUtils.isNotBlank(o.getClassId())).collect(Collectors.groupingBy(o -> o.getClassId()));
        //查询时间段
        List<Map<String,Object>> ruleList = new ArrayList<>();
        Map<String, List<Map<String,Object>>> timePeriodByClassIdValue = new HashMap<>();

        String nowData = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        //是否需要上班，0为工作日，1为休息日
        String isnotwork = getHolidaysIsNotWork(nowData);
        //特殊日期
        if(isSpeci || "1".equals(isnotwork)){
            List<InsClassesSpecial> list = insClassesSpecialService.list();
            if(CollectionUtils.isEmpty(list))  list = new ArrayList<>();
            try {
                timePeriodByClassIdValue = list.stream().filter(o-> StringUtils.isNotBlank(o.getClassId()))
                    .map(o-> {
                        try {
                            return PropertyUtils.describe(o);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        return null;
                    }).collect(Collectors.groupingBy(o -> o.get("classId").toString()));
            }catch (Exception e){}
        }else{
            List<InsClassesCommon> list = insClassesCommonService.list();
            if(CollectionUtils.isEmpty(list))  list = new ArrayList<>();
            try {
                timePeriodByClassIdValue = list.stream().filter(o-> StringUtils.isNotBlank(o.getClassId()))
                    .map(o-> {
                        try {
                            return PropertyUtils.describe(o);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        return null;
                    }).collect(Collectors.groupingBy(o -> o.get("classId").toString()));
            }catch (Exception e){}
        }

        if(CollectionUtils.isNotEmpty(classesList)){
            for (InsClasses insClasses : classesList) {
                String classId = insClasses.getId();
                //通过班次过滤人员
                List<InsClassesUser> users = userByClassIdValue.get(classId);
                if(CollectionUtils.isEmpty(users)){
                    continue;
                }
                List<String> userIds = new ArrayList<>();
                if(CollectionUtils.isNotEmpty(users)){
                    userIds = users.stream().map(o -> o.getUserId()).collect(Collectors.toList());
                }
                //通过班次过滤出线路
                List<InsClassesLine> lines = lineByClassIdValue.get(classId);
                //通过班次过滤出打卡区间
                List<Map<String, Object>> times = timePeriodByClassIdValue.get(classId);
                //循环打卡区间配置数据
                if(CollectionUtils.isNotEmpty(times) && CollectionUtils.isNotEmpty(lines)){
                    for (Map<String, Object> time : times) {
                        //巡检次数 对应生成任务数量
                        Integer classPollNum = time.get("classPollNum")==null?1:(Integer) time.get("classPollNum");
                        for (Integer i = 0; i < classPollNum; i++) {
                            //循环线路
                            for (InsClassesLine line : lines) {
                                InsLine insLine = insLineService.getById(line.getLineId());
                                // 一条线路一个任务
                                if(null != insLine) {
                                    InsTask insTask = new InsTask();
                                    JSONObject formData = new JSONObject();
                                    String taskNo = (String) FillRuleUtil.executeRule("shop_order_num",formData);

                                    SysDepart sysDepart = sysDepartService.getById(insClasses.getDepartId());
                                    String deptName = Objects.isNull(sysDepart)?"":sysDepart.getDepartName();
                                    insTask.setTaskName(deptName + insClasses.getClassName() + insLine.getLineName() + ("0".equals(insClasses.getTaskClass())?"全天全覆盖":"单次全覆盖") + "巡检任务");
//                                    insTask.setTaskType(rule.getRuleType());
                                    insTask.setTaskNo(taskNo);
                                    insTask.setTaskType("2");
                                    insTask.setTaskStatus("1");
                                    insTask.setTaskBegin(taskBegin);
                                    insTask.setTaskEnd(taskEnd);
                                    insTask.setInspectedNum(0);
                                    insTask.setClassId(classId);
                                    insTask.setTaskClass(insClasses.getTaskClass());

                                    insTask.setClassTimePre(time.get("classTimePre").toString());
                                    insTask.setClassTimeEnd(time.get("classTimeEnd").toString());
                                    //设置用户ID
                                    if(CollectionUtils.isNotEmpty(userIds)){
                                        //获取用户名称
                                        List<String> finalUserIds = userIds;
                                        List<String> userNames = sysUserList.stream().filter(o -> finalUserIds.contains(o.getUsername())).map(o->o.getRealname()).collect(Collectors.toList());
                                        if(CollectionUtils.isNotEmpty(userNames)){
                                            insTask.setUserName(Strings.join(userNames, ','));
                                        }
                                        insTask.setUserId(Strings.join(userIds.listIterator(), ','));

                                        //通过userId获取部门ID
                                        List<String> userDeptIds = sysDeptList.stream().filter(o -> finalUserIds.contains(userNameByIdValue.get(o.getUserId()))).map(o -> o.getDepartId()).collect(Collectors.toList());
                                        List<String> userDeptNames = sysDeptList.stream().filter(o -> finalUserIds.contains(userNameByIdValue.get(o.getUserId()))).map(o -> o.getDepartName()).collect(Collectors.toList());
                                        userDeptIds = toSetList(userDeptIds);
                                        userDeptNames = toSetList(userDeptNames);
                                        insTask.setDeptId(Strings.join(userDeptIds.listIterator(), ','));
                                        insTask.setDeptName(Strings.join(userDeptNames.listIterator(), ','));
                                    }
                                    // 值班部门
//                                    if("6".equals(executeCycle)) {
//                                        // 值班
//                                        int dayOfWeek = DateUtil.dayOfWeek(new Date());
//
//                                        List<InsRuleDuty> dutyList = insRuleDutyService.list(Wrappers.<InsRuleDuty>lambdaQuery()
//                                                .eq(InsRuleDuty::getRuleId, rule.getId()).eq(InsRuleDuty::getWeek, dayOfWeek));
//
//                                        if(CollUtil.isNotEmpty(dutyList)) {
//                                            insTask.setDeptId(dutyList.get(0).getDeptId());
//                                        }
//                                    }
                                    insTaskService.save(insTask);

                                    // 一条线路的所有点位
                                    List<InsLinePoint> linePoints = insLinePointService.list(Wrappers.<InsLinePoint>lambdaQuery().eq(InsLinePoint::getLineId, line.getLineId()));

                                    if(CollUtil.isNotEmpty(linePoints)) {
                                        for(InsLinePoint linePoint : linePoints) {
                                            InsPoint insPoint = insPointService.getById(linePoint.getPointId());
                                            if(null != insPoint) {
                                                InsTaskItem taskItem = new InsTaskItem();
                                                taskItem.setItemName(insPoint.getPointName());
                                                taskItem.setItemStatus("1");
                                                taskItem.setTaskId(insTask.getId());
                                                taskItem.setLineId(line.getLineId());
                                                taskItem.setPointId(insPoint.getId());
                                                taskItem.setClassTimePre(time.get("classTimePre").toString());
                                                taskItem.setClassTimeEnd(time.get("classTimeEnd").toString());
                                                insTaskItemService.save(taskItem);
                                            }
                                        }
                                        //总点位数
                                        insTask.setPointNum(linePoints.size());
                                        insTask.setTaskClass(classId);
                                        insTask.setTaskClass(insClasses.getTaskClass());
                                        insTaskService.updateById(insTask);
                                    }
                                }
                            }
                        }
                    }
                }

                // ==================== 发送短信开始 ===============================
                String phones = "";

                List<SysUser> sysUsers = sysUserService.listByIds(userIds);
                List<String> userNames = sysUsers.stream().map(SysUser::getUsername).collect(Collectors.toList());

                if(CollUtil.isNotEmpty(userNames)) {
                    List<String> sendPhones = new ArrayList<>();
                    for(String userName : userNames) {
                        // 查询人员所在部门是否为厂领导
                        List<String> departIds = sysBaseApi.getDepartIdsByUsername(userName);
                        if(departIds.contains(insClasses.getDepartId())) {
                            LoginUser loginUser = sysBaseApi.getUserByName(userName);
                            sendPhones.add(loginUser.getPhone());
                        }
                    }
                    if(CollUtil.isNotEmpty(sendPhones)) {
                        phones = String.join(",", sendPhones.stream().map(String::valueOf).distinct().collect(Collectors.toList()));
                    }
                }

                if(StrUtil.isNotEmpty(phones)) {
                    log.debug("发送短信提醒厂领导：" + phones);

                    // 发送厂领导任务生成短信提醒
                    String smsContent = "您有新的走动式巡检任务生成，截止日期" + DateUtil.format(taskEnd, "yyyy-MM-dd HH:mm:ss") + "请注意查收！";
                    SmsUtil.sendMas(phones.split(","), smsContent);
                }
                // 发送短信结束
            }
        }
    }

    //是否需要上班，0为工作日，1为休息日
    public String getHolidaysIsNotWork(String now) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        String url = "https://apis.tianapi.com/jiejiari/index?key=3950b924e669b8044168c5a91787fb4e&date="+now+"&type=0";
        HttpPost httpPost = new HttpPost(url);

        try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
            HttpEntity entity = response.getEntity();
            String result = EntityUtils.toString(entity);
            JSONObject resJson = JSONObject.parseObject(result);
            if(!"200".equals(resJson.get("code").toString())){
                throw new RuntimeException("获取节假日失败，"+resJson.get("msg").toString());
            }
            JSONArray list = (JSONArray)((JSONObject)resJson.get("result")).get("list");
            if(!list.isEmpty()){
                for (Object o : list) {
                    JSONObject j = (JSONObject)o;
                    String date = j.get("date").toString();
                    String isnotwork = j.get("isnotwork").toString();//是否需要上班，0为工作日，1为休息日
                    if(now.equals(date)){
                        return isnotwork;
                    }
                }
            }
            System.out.println(result);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
    @Value("${deleteBackupDataParam.backupFilePath}")
    private String backupFilePath;//备份文件储存位置
    @Value("${deleteBackupDataParam.delCycle}")
    private String delCycle;//备份周期 单位：天
    @Value("${deleteBackupDataParam.delBackupKey}")
    private String delBackupKey;//删除数据功能模块key 多个逗号分隔

    /**
     * 定时删除任务 巡检记录表数据 并备份
     */
    @Override
    public void deleteBackupData() {
        if(StringUtils.isBlank(delCycle)){
            throw new RuntimeException("请配置需要备份删除的数据有效日期！");
        }

        if(StringUtils.isBlank(delBackupKey)){
            throw new RuntimeException("请配置需要备份删除的数据主表！");
        }
        //开始备份
        insDeleteBackupService.backupTable(delBackupKey);
    }

    public static boolean isToday(Date date) {
        if(date==null){
            return false;
        }
        Calendar today = Calendar.getInstance();
        Calendar specifiedDate = Calendar.getInstance();
        specifiedDate.setTime(date);

        return today.get(Calendar.YEAR) == specifiedDate.get(Calendar.YEAR)
                && today.get(Calendar.MONTH) == specifiedDate.get(Calendar.MONTH)
                && today.get(Calendar.DAY_OF_MONTH) == specifiedDate.get(Calendar.DAY_OF_MONTH);
    }


    public List<String> toSetList(List<String> list){
        List<String> newList = new ArrayList<>();
        if(CollectionUtils.isEmpty(list)){
            return newList;
        }
        for (String s : list) {
            if(!newList.contains(s)){
                newList.add(s);
            }
        }
        return newList;
    }


}
